package edu.yuhf.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.yuhf.dbutils.DBConnection;
import org.apache.log4j.Logger;

import com.yuhf.dbutils.TransactionManager;

import edu.yuhf.dao.iface.HobbyDao;
import edu.yuhf.dao.iface.NativePlaceDao;
import edu.yuhf.dao.iface.UserDao;
import edu.yuhf.dao.iface.UserDetailDao;
import edu.yuhf.dao.mysql.HobbyJdbcDaoImpl;
import edu.yuhf.dao.mysql.NativePlaceJdbcDaoImpl;
import edu.yuhf.dao.mysql.UserDetailJdbcDaoImpl;
import edu.yuhf.dao.mysql.UserJdbcDaoImpl;
import edu.yuhf.domain.Hobby;
import edu.yuhf.domain.NativePlace;
import edu.yuhf.domain.Page;
import edu.yuhf.domain.User;
import edu.yuhf.domain.UserDetail;
import edu.yuhf.service.iface.UserService;

public class UserServiceImpl implements UserService {
	
	private static Logger log=Logger.getLogger(UserServiceImpl.class);
	
	private UserDao userDao=new UserJdbcDaoImpl();
	private UserDetailDao userDetailDao=new UserDetailJdbcDaoImpl();
	private HobbyDao hobbyDao=new HobbyJdbcDaoImpl();
	private NativePlaceDao nativePlaceDao=new NativePlaceJdbcDaoImpl();

	@Override
	/**
	 * 适配单id和多id的情况，形如：1或1,2,3
	 */
	public boolean deleteUser(String ids) {
		boolean flag=false;
		String[] temp=null;
		if(ids.contains(",")){
			temp=ids.split(",");
		}else{
			temp=new String[]{ids};
		}
		List<Integer> userIds=new ArrayList<>();
		TransactionManager tm=new TransactionManager();
		try {
			tm.beginTransaction();
			//TODO:缺少用户角色表中数据的删除操作
			//根据用户id,查出对应的用户详情表中的数据
			for(int i = 0,len=temp.length;i<len;i++) {
				int userId=userDetailDao.getIdByUserId(Integer.valueOf(temp[i]));
				userIds.add(userId);
			}
			String strUserIds="";
			for(Integer element:userIds){
				if("".equals(strUserIds)) {
					strUserIds+=element;
				}else {
					strUserIds+=",";
					strUserIds+=element;
				}
			}
			log.debug("strUserIds is:"+strUserIds);
			//先删除用户详情表中的相应数据，再删除用户表中的相应数据
			if(userDetailDao.deleteUserDetail(strUserIds)>=0) {
				if(userDao.deleteUser(ids)>0) {
					flag=true;
				}
			}
			tm.commit();
		} catch (SQLException e) {
			tm.rollback();
			e.printStackTrace();
		}

		return flag;
	}
	
	@Override
	public Optional<User> checkUserNameAndPassword(String userName, String password)  {
		int id=0;
		Optional<User> optional=Optional.empty();
		TransactionManager tm=new TransactionManager();
		try {
			tm.beginTransaction();
			if(1==userDao.queryUserForNameAndPwd(userName, password)) {
				optional=userDao.queryUser(userName,password);
			}
			tm.commit();
		} catch (SQLException e) {
			tm.rollback();
			e.printStackTrace();
		}
		return optional;
	}

	@Override
	public boolean checkUserName(String userName) {
		boolean flag=false;
		if(userDao.checkUserName(userName)==0) {
			flag=true;
		}
		return flag;
	}

	@Override
	public boolean insertUserInfo(User user, UserDetail userDetail) {
		boolean flag=false;
		int rowNumber=0;
		TransactionManager tm=new TransactionManager();
		try {
			tm.beginTransaction();
			int userId=userDao.insertForUserId(user);
			if(0!=userId) {
				userDetail.setUserId(userId);
				rowNumber=userDetailDao.insertUserDetail(userDetail);
			}
			tm.commit();
		} catch (SQLException e) {
			tm.rollback();
		}
		if(rowNumber!=0) {
			flag=true;
		}
		return flag;
	}

	@Override
	public List<Map<String, Object>> queryAllUserAndUserDetail() {
		List<Map<String,Object>> list=userDao.queryAllUserAndUserDetail();
		List<Hobby> hobbies=hobbyDao.getHobbies();
		if(null!=list&&null!=hobbies) {
			list.stream().filter(element->null!=element.get("hobby_code")).forEach((element)->{
				String temp=(String) element.get("hobby_code");
				for(Hobby hobby:hobbies) {
					temp=temp.replace(String.valueOf(hobby.getCode()), hobby.getName());
				}
				element.put("hobby_code", temp);
			});
			list.stream().filter(element->null!=element.get("np_code")).forEach((element)->{
				String nativePlaceName=(String)element.get("np_code");
				NativePlace nativePlace=nativePlaceDao.getProvinceByCode(nativePlaceName.substring(0,2));
				element.put("name", nativePlace.getName()+","+element.get("name"));			
			});
		}
		return list;
	}

	@Override
	public Optional<Map<String, Object>> queryUserAndUserDetailById(int id) {
		Map<String,Object> uaud=userDao.queryUserAndUserDetailById(id);
		Optional<Map<String,Object>> optional=Optional.ofNullable(uaud);
		return optional;
	}

	@Override
	public boolean updateUserAndUserDetail(User user, UserDetail ud) {
		boolean flag=false;
		TransactionManager tm=new TransactionManager();
		try {
			tm.beginTransaction();
			int userRowNumber=userDao.updateUser(user);
			int userDetailRowNumber=userDetailDao.updateUserDetail(ud);
			if(userRowNumber==1&&userDetailRowNumber==1) {
				flag=true;
			}
			tm.commit();
		} catch (SQLException e) {
			tm.rollback();
			e.printStackTrace();
		}
		return flag;
	}

	@Override
	public void queryAllUserAndUserDetail(final Page<List<Map<String,Object>>> page) {
		userDao.queryAllUserAndUserDetailByPage(page);
		List<Hobby> hobbies=hobbyDao.getHobbies();
		if(null!=page.getList()&&null!=hobbies) {
			//替换表中爱好字段，把数值替换成文本。
			page.getList().stream().filter(element->null!=element.get("hobbyCode")).forEach((element)->{
				String temp=(String) element.get("hobbyCode");
				for(Hobby hobby:hobbies) {
					temp=temp.replace(String.valueOf(hobby.getCode()), hobby.getName());
				}
				element.put("hobbyName", temp);
			});
			//为城市前面加上其所在的省份，形如：山东，济南
			page.getList().stream().filter(element->null!=element.get("npCode")).forEach((element)->{
				String npCode=(String)element.get("npCode");
				NativePlace nativePlace=nativePlaceDao.getProvinceByCode(npCode.substring(0,2));
				NativePlace cityNP=nativePlaceDao.getCityByCode(npCode);
				element.put("npName", nativePlace.getName()+","+cityNP.getName());
			});
		}
		int totalRowNumber=0;
		//获取总行数
		if("".equals(page.getKeyword())){
			totalRowNumber=userDao.queryTotalRowNumber();
		}else {
			totalRowNumber=userDao.queryTotalRowNumber(page.getKeyword());
		}
		page.setTotalRowNumber(totalRowNumber);
		int totalPageNumber=0==totalRowNumber%page.getPageNumber()?totalRowNumber/page.getPageNumber():totalRowNumber/page.getPageNumber()+1;
		page.setTotalPageNumber(totalPageNumber);
	}

	@Override
	public Optional<User> getUser(int id) {
		return userDao.queryUserById(id);
	}


}
